import { _decorator, Component, director, Node } from 'cc';
import { GGStore } from '../../../framework/core/base/GGStore';
import { EVENT_NAMES, GAME_DATA_ENUMS } from '../../../common/src/util/Enums';
import Config from '../../../common/src/util/Config';
import DataMgr from '../../../common/src/util/DataMgr';
const { ccclass, property } = _decorator;

@ccclass('TimeManager')
export class TimeManager extends Component {

    // =======================================
    // Component 生命周期
    // =======================================
    start() {
        director.addPersistRootNode(this.node)
    }

    update(deltaTime: number) {
        if (DataMgr.stamina < 6) {
            const nowStamp = Date.now()
            const timeGo = Math.floor((nowStamp - this.lastSaveTime) / 1000)
    
            // 需要增加一个体力
            if (timeGo > Config.staminaAddDuration) {
                const addStamina = Math.floor(timeGo / Config.staminaAddDuration)
                if ((addStamina + DataMgr.stamina) > Config.maxStamina) {
                    DataMgr.stamina = Config.maxStamina
                } else {
                    DataMgr.stamina = DataMgr.stamina + addStamina
                }
                
                this.lastSaveTime = nowStamp
                gg.systemEvent.emit(EVENT_NAMES.UPDATE_START_INFO)
            }
        }
    }
    
    // =======================================
    // Component Set Get 用来保存本地数据
    // =======================================
    // 上一次保存的增加时间
    private _lastSaveTime = null
    public set lastSaveTime(v: number) {
        this._lastSaveTime = v
        GGStore.set(GAME_DATA_ENUMS.LAST_STAMINA_TIME, this._lastSaveTime)
    }

    public get lastSaveTime(): number {
        if (this._lastSaveTime == null) {
            this._lastSaveTime = GGStore.get(GAME_DATA_ENUMS.LAST_STAMINA_TIME, Date.now())
        }

        return this._lastSaveTime
    }
}


